﻿using MvcPaging;
using Ninject;
using Peninsula.DataAccess;
using Peninsula.DataAccess.POCO;
using Peninsula.Site.Data.Constant;
using Peninsula.Site.Data.Models;
using Peninsula.Site.Data.Result;
using Peninsula.Utility.Extensions;
using Peninsula.Web.Infrastructure;
using Peninsula.Web.Models.RepairOrder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Peninsula.Web.Controllers
{
    public class RepairOrderController : HouseholdsBaseController
    {


        TotalList list = new TotalList();


        string[]  CateporyMonth =  new string[] { "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月" };

        [Inject]
        public IServices.IHouseholdsRestatisticsService HouseholdsRestatisticsService { get; set; }

        [Inject]
        public IServices.IStoreRestatisticsService StoreRestatisticsService { get; set; }

        [Inject]
        public IServices.IRepairOrderService RepairOrderService { get; set; }
        [Inject]
        public IServices.IItemTypeService ItemTypeService { get; set; }
        [Inject]
        public IServices.ISiteFileService SiteFileService { get; set; }
        // GET: RepairOrder

        /// <summary>
        /// 订单跟踪
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        public ActionResult Index( RepairOrderPagedListModel viewModel)
        {
            SetBreadcrumb(currentName: "所有订单", parentName: "订单跟踪");
            SetPageTitle("订单跟踪"); 
            IQueryable<RepairOrder> query = RepairOrderService.Entities.Where(r => r.Status==OrderStatus.Submitted||r.Status==OrderStatus.Received||r.Status==OrderStatus.Sent
            ||r.Status==OrderStatus.OnTheWay||r.Status==OrderStatus.RepairFinished);
            query = query.Where(r => r.HouseholdsId == HouseholdsSession.Identity);
            if (viewModel.Keyword.IsNotNullAndNotWhiteSpace())
            {
                query = query.Where(r => r.Name.Contains(viewModel.Keyword)||r.ItemType.Name.Contains(viewModel.Keyword));
            }
            if (viewModel.hdOrderStatus.HasValue)
            {
                query = query.Where(r => r.Status.ToString() == viewModel.hdOrderStatus.ToString());
            }
            viewModel.PagedList = query.OrderByDescending(s => s.CreatedTime).ToPagedList(viewModel.PageIndex, viewModel.Size);
            viewModel.QueryParameter = GetParameterFromQueryString();
            return View(viewModel);
        }

        /// <summary>
        /// 创建或修改订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CreateOrEditRepairOrder(string id = null) {

            RepairOrder repairOrder = RepairOrderService.GetById(id);
            RepairOrderCreateOrEditModel model = new RepairOrderCreateOrEditModel();
            model.ItemTypes = ItemTypeService.Entities.Select(
                  m => new SelectListItem()
                  {
                      Value = m.Id,
                      Text = m.Name
                  }).ToList();
            model.IsEdit = repairOrder.IsNotNull();
            if (model.IsEdit)
            {
                var images = repairOrder.SiteFiles
                                        .Where(f => f.Type == SiteFileType.MaintenanceImage)
                                        .OrderByDescending(t => t.CreatedTime).ToList();
                var deleteUrl = Url.Action("DeleteFile", "Common");
                model.Id = repairOrder.Id;
                model.Name = repairOrder.Name;
                model.Description = repairOrder.Description;
                model.Appointment = repairOrder.Appointment;
                model.ItemType = repairOrder.ItemType;
                model.ItemTypeId = repairOrder.ItemTypeId;
                model.JQueryFileInputModel.Previews = images.Select(img => new JQueryFileInputPreviewModel
                                                      { Src = Url.Content(img.Path)}).ToList();
                model.JQueryFileInputModel.initialPreviewConfig = images.Select(img => new JQueryFileInputPreviewConfigModel
                                                         { url = deleteUrl, extra = new { id = img.Id } ,width="80px" }).ToList();
                model.JQueryFileInputModel.maxFileCount = 5;

                //model.ItemTypes = ItemTypeService.Entities.Select(
                //m => new SelectListItem()
                //{
                //    Value = m.Id,
                //    Text = m.Name
                //}).ToList();

            }
            var EditType = model.IsEdit ? "编辑" : "新增";
            SetBreadcrumb(EditType + "维修订单", parentName: "物品报修");
            SetPageTitle("物品报修");
            return View(model);

        }


        /// <summary>
        /// 创建或修改订单
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateOrEditRepairOrder(RepairOrderCreateOrEditModel post) {
            JsonResultData result = new  JsonResultData();

            result.RunWithTry(r=> {
                if (ModelState.IsValid)
                {
                    RepairOrder repairOrder = post.IsEdit ? RepairOrderService.GetById(post.Id) : new RepairOrder();
                    if (repairOrder.IsNull())
                    {
                        r.AddMessage("订单不存在");
                        return;
                    }
                    repairOrder.Name = post.Name;
                    repairOrder.ItemTypeId = post.ItemTypeId;
                    repairOrder.Description = post.Description;
                    repairOrder.Appointment = post.Appointment;
                    repairOrder.HouseholdsId = HouseholdsSession.Identity;
                    SaveFiles(FileSaveRule.RepairOrderImageMonthlySavePath,imgSrc=> {
                        repairOrder.SiteFiles.Add(new SiteFile { Type = SiteFileType.MaintenanceImage, Path = imgSrc });
                    });
                    bool isSuccess = false;
                    if (post.IsEdit)
                    {
                        repairOrder.Status = OrderStatus.Submitted;
                        repairOrder.SetUpdateInfo(HouseholdsSession.UserName);
                        isSuccess = RepairOrderService.Update(repairOrder) > 0;
                    }
                    else
                    {
                        repairOrder.SetCreateAndUpdateInfo(HouseholdsSession.UserName);
                        isSuccess = RepairOrderService.Insert(repairOrder) > 0;
                    }
                    r.Success = isSuccess;
                    r.AddMessage("提交" + (r.Success ? "成功" : "失败"));
                    if (post.IsEdit)
                    {
                        r.RedirectUrl = Url.Action("Index");
                    }
                    else
                    {
                        r.RedirectUrl = Url.Action("Index", "Home");
                    }
                   

                }
                else {
                    result.AddModelValidErrorMessage(ModelState);

                }
            });

            return Json(result);
        }


        
        /// <summary>
        /// 删除订单--物理
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(string id) {

            JsonResultData result = new JsonResultData();
            result.RunWithTry(data=> {
                if (ModelState.IsValid)
                {

                    var order = RepairOrderService.GetById(id);
                    if (order.Status != OrderStatus.Abandoned)
                    {
                        if (order.EndTime.Value.Year == DateTime.Now.Year && order.EndTime.Value.Month == DateTime.Now.Month && order.Status == OrderStatus.AlreadyPaid)
                        {
                            result.Success = false;
                            result.AddMessage("该订单处于" + DateTime.Now.Year.ToString() + "年"
                                + DateTime.Now.Month.ToString() + "月时间段，并未统计，不可删除！");
                            result.ReloadPage = true;
                        }
                        else
                        {
                            var images = order.SiteFiles.ToList();
                            var DelImages = images.Select(f => f.Id).ToArray();
                            images.ForEach(s => order.SiteFiles.Remove(s));
                            SiteFileService.DeleteFiles(DelImages);
                            //var DelImages=order.SiteFiles.Where()

                            result.Success = RepairOrderService.Delete(order) > 0;
                            result.AddMessage("删除" + (result.Success ? "成功" : "失败"));
                            if (result.Success)
                            {
                                result.ReloadPage = true;

                            }
                        }


                    }
                    else
                    {
                        var images = order.SiteFiles.ToList();
                        var DelImages = images.Select(f => f.Id).ToArray();
                        images.ForEach(s => order.SiteFiles.Remove(s));
                        SiteFileService.DeleteFiles(DelImages);
                        //var DelImages=order.SiteFiles.Where()

                        result.Success = RepairOrderService.Delete(order) > 0;
                        result.AddMessage("删除" + (result.Success ? "成功" : "失败"));
                        if (result.Success)
                        {
                            result.ReloadPage = true;

                        }

                    }
                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            });
            return JsonAllowGet(result);
        }

        /// <summary>
        /// 删除已提交  ，但写错了，想重新报修物品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DeleteSumbit(string id)
        {

            JsonResultData result = new JsonResultData();
            result.RunWithTry(data => {
                if (ModelState.IsValid)
                {

                    var order = RepairOrderService.GetById(id);
                        var images = order.SiteFiles.ToList();
                        var DelImages = images.Select(f => f.Id).ToArray();
                        images.ForEach(s => order.SiteFiles.Remove(s));
                        SiteFileService.DeleteFiles(DelImages);
                        //var DelImages=order.SiteFiles.Where()

                        result.Success = RepairOrderService.Delete(order) > 0;
                        result.AddMessage("删除" + (result.Success ? "成功" : "失败"));
                        if (result.Success)
                        {
                            result.ReloadPage = true;

                        }
                    }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            });
            return JsonAllowGet(result);
        }


        /// <summary>
        /// 订单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Details(string id) {
            SetBreadcrumb(currentName: "订单详情", parentName: "主页");
            SetPageTitle("主页");
            RepairOrder model = RepairOrderService.GetById(id);
            return View(model);
        }


        /// <summary>
        /// 完成订单
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        public ActionResult AlreadyPaidDetalis(RepairOrderPagedListModel viewModel) {

            SetBreadcrumb(currentName: "所有订单", parentName: "完成订单");
            SetPageTitle("完成订单");
            IQueryable<RepairOrder> query = RepairOrderService.Entities.Where(r => r.Status == OrderStatus.AlreadyPaid || r.Status == OrderStatus.HhouseholdToGoOut||r.Status==OrderStatus.Abandoned);
             query=query.Where(r=>r.HouseholdsId == HouseholdsSession.Identity);
            if (viewModel.Keyword.IsNotNullAndNotWhiteSpace())
            {
                query = query.Where(r => r.Name.Contains(viewModel.Keyword) || r.ItemType.Name.Contains(viewModel.Keyword));
            }
            if (viewModel.fOrderStatus.HasValue)
            {
                query = query.Where(r => r.Status.ToString() == viewModel.fOrderStatus.ToString());
            }
            viewModel.PagedList = query.OrderByDescending(s => s.UpdatedTime).ToPagedList(viewModel.PageIndex, viewModel.Size);
            viewModel.QueryParameter = GetParameterFromQueryString();
            return View(viewModel);
        }


        /// <summary>
        /// 支付订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Payment(string id)
        {
            JsonResultData result = new JsonResultData();

            result.RunWithTry(order => {

                if (ModelState.IsValid)
                {
                    RepairOrder repairOrder = RepairOrderService.GetById(id);
                    if (repairOrder.IsNull())
                    {
                        order.Success = false;
                        order.AddMessage("订单未存在！");
                    }
                    repairOrder.Status = OrderStatus.AlreadyPaid;
                    repairOrder.SetUpdateInfo(HouseholdsSession.UserName);
                    order.Success = RepairOrderService.Update(repairOrder) > 0;
                    order.AddMessage("支付" + (order.Success ? "成功" : "失败"));
                    if (order.Success)
                    {
                        order.ReloadPage = true;
                    }
                }
                else
                {
                    order.AddModelValidErrorMessage(ModelState);
                }

            });

            return JsonAllowGet(result);
        }


        /// <summary>
        /// 户主统计
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult HouseholdsTotal() {

            SetBreadcrumb(currentName: "订单统计", parentName: "主页");
            SetPageTitle("订单统计");
            return View();
        }
        /// <summary>
        /// 户主统计
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult HouseholdsTotal(TotalYearModel post)
        {
            JsonResultData data = new JsonResultData();
            var year = HttpContext.Request.Form["dateKeyWord"];
            if (year=="")
            {
                data.Success = false;
                data.AddMessage( "统计年份不能为空！");
                return Json(data);
            }
            DateTime StartTotalTime = new DateTime(int.Parse(year), 1, 1);

          
            //添加横坐标
            foreach (var item in CateporyMonth)
            {
                list.listCatepory.Add(item);
            }

            Series number = new Series()
            {
                id = 0,
                name = "订单数量",
                type = "bar",
                data = new List<double>(),
                itemStyle = new itemStyle { normal = new normal { color = "#2EC7C9" } },
                markPoint = new markPoint { data = new List<data>() { new data { type = "max", name = "最大值" }, new data { type = "min", name = "最小值" } } },
                markLine = new markLine { data = new List<data>() { new data { type = "average", name = "平均值" } } }

            };

            Series money = new Series()
            {
                id = 1,
                name = "订单钱款",
                type = "bar",
                data = new List<double>(),
                itemStyle = new itemStyle { normal = new normal { color = "#FFBB73" } },
                markPoint = new markPoint { data = new List<data>() { new data { type = "max", name = "最大值" }, new data { type = "min", name = "最小值" } } },
                markLine = new markLine { data = new List<data>() { new data { type = "average", name = "平均值" } } }

            };

            
           

            if (StartTotalTime.Year == DateTime.Now.Year)//今年
            {
                IQueryable<HouseholdsRestatistics> query = HouseholdsRestatisticsService.Entities;
                for (DateTime dt = StartTotalTime; dt < DateTime.Now; dt=dt.AddMonths(1))
                {
                  query =  query.Where(q => q.TotalDateTime.Value.Year == dt.Year && q.TotalDateTime.Value.Month == dt.Month && q.HouseholdsId ==HouseholdsSession.Identity);
                   var householdsRestatistics = query.SingleOrDefault();
                    if (query.Count() == 0)
                    {
                        number.data.Add(0);
                        money.data.Add(0);
                    }
                    else
                    {
                        number.data.Add(householdsRestatistics.Number);
                        money.data.Add(householdsRestatistics.TotalPrice.AsDouble());
                    }
                }

               
            }
            else if (StartTotalTime.Year < DateTime.Now.Year) //过去
            {
                DateTime FinishDateTime = StartTotalTime.AddYears(1);
                IQueryable<HouseholdsRestatistics> query = HouseholdsRestatisticsService.Entities;
                for (DateTime dt = StartTotalTime; dt < FinishDateTime; dt = dt.AddMonths(1))
                {
                    query = query.Where(q => q.TotalDateTime.Value.Year == dt.Year && q.TotalDateTime.Value.Month == dt.Month && q.HouseholdsId == HouseholdsSession.Identity);
                    var householdsRestatistics = query.SingleOrDefault();
                    if (query.Count()==0)
                    {
                        number.data.Add(0);
                        money.data.Add(0);
                    }
                    else
                    {
                        number.data.Add(householdsRestatistics.Number);
                        money.data.Add(householdsRestatistics.TotalPrice.AsDouble());
                    }
                   
                }

            }
            else if (StartTotalTime.Year > DateTime.Now.Year)//将来
            {

            }
            else
            {

            }
            list.listLegend.Add(number.name);
            list.listLegend.Add(money.name);
            list.listSeries.Add(number);
            list.listSeries.Add(money);
            return Json(list);

        }

    }


}